package com.guet.service.impl;

import com.guet.DTO.UserLoginDTO;
import com.guet.Entity.User;
import com.guet.constant.UserConstant;
import com.guet.exception.AccountNotFoundException;
import com.guet.exception.PasswordErrorException;
import com.guet.exception.StatusErrorException;
import com.guet.mapper.LoginMapper;
import com.guet.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String account = userLoginDTO.getAccount();
        String password = userLoginDTO.getPassword();
        String identify = userLoginDTO.getIdentify();

        User user = loginMapper.query(account, identify);


        if (user == null) {
            throw new AccountNotFoundException("用户不存在");
        }
        // MD5密码加密后于数据库的密码进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!user.getPassword().equals(password)) {
            throw new PasswordErrorException("用户名或密码错误");
        }
        if (user.getStatus().equals(UserConstant.USER_DISABLED)){
            throw new StatusErrorException("该账号已被禁用，请联系管理员");
        }
        return user;
    }
}
